package com.example.mydemo.config;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import lombok.extern.slf4j.Slf4j;

 @Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String uri = request.getRequestURI();

        System.out.println("拦截器进入uri="+uri);

        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        if (user == null) {
            // 用户未登录，重定向到登录页面
            //response.setContentType("text/html;charset=UTF-8");
            response.sendRedirect("/login");
            return false;
        }
        return true;
    }

//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        log.info("LoginInterceptor postHandle(目标方案执行后执行).....");
//    }
//
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        log.info("LoginInterceptor afterCompletion(视图渲染完毕后执行,最后执行).....");
//    }
}